package xyf.p11.other;

/**
 * ClassName: M0105_OneEdit
 * Description:
 * Author: xyf
 * Date: 9/18/22 10:53 AM
 * Version: 1.0
 **/
public class M0105_OneEdit
{
    public boolean oneEditAway(String first, String second)
    {
        if (first.length() == second.length() - 1)
        {
            return oneInsert(first, second);
        }
        else if (first.length() == second.length() + 1)
        {
            return oneInsert(second, first);
        }
        else if (first.length() == second.length())
        {
            int diffCnt = 0;
            for (int i = 0; i < first.length(); i++)
            {
                if (first.charAt(i) != second.charAt(i))
                {
                    diffCnt += 1;
                }
                if (diffCnt > 1)
                {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    private boolean oneInsert(String shorter, String longer)
    {
        int indexS = 0;
        int indexL = 0;

        while (indexS < shorter.length() && indexL < longer.length())
        {
            if (shorter.charAt(indexS) == longer.charAt(indexL))
            {
                indexS++;
            }
            indexL++;
            if (indexL - indexS > 1)
            {
                return false;
            }
        }

        return true;
    }
}